package com.cq.androidtools.text

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Rect
import android.util.AttributeSet
import android.util.Log
import android.util.TypedValue
import android.view.View
import com.cq.androidtools.R

/**
 * 作者: CQ
 * 日期: 2022-07-12
 * 说明:
 */
class TextNovel @JvmOverloads constructor(
    context : Context, attrs : AttributeSet? = null, defStyleAttr : Int = 0
) : View(context, attrs, defStyleAttr) {
    private var mBound : Rect = Rect()
    private var mPaint : Paint = Paint()

    init {
        val typeArray = context.theme.obtainStyledAttributes(attrs, R.styleable.CustomViewRandomInteger, defStyleAttr, 0)
        for (i in 0 until typeArray.length()) {
            val attr = typeArray.getIndex(i)
            if (attr == R.styleable.CustomViewRandomInteger_titleTextColor) {
                // 默认颜色设置为黑色
                val mTitleTextColor = typeArray.getColor(attr, Color.BLACK)
                /**
                 * 获得绘制文本的颜色
                 */
                mPaint.color = mTitleTextColor
            } else if (attr == R.styleable.CustomViewRandomInteger_titleTextSize) {
                // 默认设置为16sp，TypeValue也可以把sp转化为px
                val mTitleTextSize = typeArray.getDimensionPixelSize(attr,
                    TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 16f, resources.displayMetrics).toInt())
                mPaint.textSize = mTitleTextSize.toFloat()
            }
        }
        mPaint.isAntiAlias = true
        typeArray.recycle()
    }

    override fun onMeasure(widthMeasureSpec : Int, heightMeasureSpec : Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        val width = MeasureSpec.getSize(widthMeasureSpec)
        val height = MeasureSpec.getSize(heightMeasureSpec)
        setMeasuredDimension(width, height)
        Log.e("测量", "width = $width, height = $height")
    }


    override fun onDraw(canvas : Canvas?) {
        super.onDraw(canvas)
        Log.e("onDraw", "width = $width, height = $height")
        val text = getDataXS()
        val w = mPaint.measureText(text)
        Log.e("onDraw", "w = $w")
        Log.e("onDraw", "w = ${mPaint.measureText(",")}")
        Log.e("onDraw", "w = ${mPaint.measureText("。")}")
        Log.e("onDraw", "w = ${mPaint.measureText("a")}")
        Log.e("onDraw", "w = ${mPaint.measureText("我")}")
        Log.e("onDraw", "w = ${mPaint.measureText(" ")}")

        val fm = mPaint.fontMetrics

        val h = fm.bottom - fm.ascent


        Log.e("onDraw", "h = $h")
        Log.e("onDraw", "h = ${height / h}")
        Log.e("onDraw", "w = ${w / width}")
        Log.e("onDraw", "大概多少个字符 = ${w / 32}")
        Log.e("onDraw", "大概多少个字符 = ${(w / 32) / (w / width)}")
        val tx = text.subSequence(0, ((w / 32) / (w / width)).toInt())
        Log.e("onDraw", "大概多少个字符 = ${tx}")
        canvas?.drawText(tx.toString(), 0f, 100f, mPaint)
    }

}